/**
 * <p>项目名：ViewPagerFragmentRadioGroup</p>
 * <p>包名：	com.my.viewpagerfragmentradiogroup</p>
 * <p>文件名：ThreeFragemtn.java</p>
 * <p>版本信息： 2.1.0</p>
 * <p>日期： 2015/5/14/13:04.</p>
 * Copyright (c) 2015帮你公司-版权所有
 */
package com.tiantianyuegou.fragment;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.AvoidXfermode;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.AdapterView;
import android.widget.GridLayout;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.tiantianyuegou.activity.BaseActivity;
import com.tiantianyuegou.R;
import com.tiantianyuegou.activity.CityListActivity;
import com.tiantianyuegou.activity.MainActivity;
import com.tiantianyuegou.activity.StoreDetailActivity;
import com.tiantianyuegou.activity.StoreListActivity;
import com.tiantianyuegou.adapter.LocalStoreAdapter;
import com.tiantianyuegou.adapter.LocalStoreModularGridAdapter;
import com.tiantianyuegou.constant.Constant;
import com.tiantianyuegou.http.ApiDefine;
import com.tiantianyuegou.http.SPHelper;
import com.tiantianyuegou.model.LocalStoreInfo;
import com.tiantianyuegou.util.LoadingDialog;
import com.tiantianyuegou.util.NetworkUtils;
import com.tiantianyuegou.view.NoScrollListView;


import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;


/**
 * 本地商城
 */
public class LocalShopFragment extends Fragment {


    private View rootView;
    private GridView grid_moudlar;
    private BaseActivity activity;
    private NoScrollListView mListView;
    private TextView city;
    private LoadingDialog loadingDialog;
    private LocalStoreModularGridAdapter mAdapter;
    private LocalStoreAdapter mStoreAdapter;
    private String TAG = "LocalShopFragment";
    private List<LocalStoreInfo> storeList;
    private List<LocalStoreInfo> storeType;
    private int page;

    private ChangeCityReceiver mChangeCityReceiver = new ChangeCityReceiver();
    //广播接收器，接收城市选择的item
    public class ChangeCityReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            city.setText(intent.getStringExtra("cityName"));
            getCityId();
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        activity = (BaseActivity) getActivity();
        if (rootView == null) {
            rootView = inflater.inflate(R.layout.fragment_localshop, container,
                    false);
        }
        ViewGroup parent = (ViewGroup) rootView.getParent();
        if (parent != null) {
            parent.removeView(rootView);
        }
        findViewByIds();
        ininListener();
        storeTypeData();
        getCityId();
        //storeListData();
        //注册广播接收器
        IntentFilter filter = new IntentFilter();
        filter.addAction(CityListActivity.CITYSELECT);
        getActivity().registerReceiver(mChangeCityReceiver, filter);
        return rootView;
    }

    public void findViewByIds() {
        grid_moudlar = (GridView) rootView.findViewById(R.id.grid_modular);
        mListView = (NoScrollListView) rootView.findViewById(R.id.localshop);
        city = (TextView) rootView.findViewById(R.id.city_name);
    }

    public void ininListener() {
        if (Constant.cName == null && "".equals(Constant.cName)) {
            city.setText("北京");
        } else {
            city.setText(Constant.cName);//从首页拿到定位城市
        }

        Log.e("TAG", "--------cname:" + Constant.cName);

        loadingDialog = new LoadingDialog(activity);
        mAdapter = new LocalStoreModularGridAdapter(activity);
        grid_moudlar.setAdapter(mAdapter);
        mStoreAdapter = new LocalStoreAdapter(activity);
        //Handler handler=new Handler();
        mListView.setAdapter(mStoreAdapter);
        storeType = new ArrayList<>();
        storeList = new ArrayList<>();
        city.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getActivity(), CityListActivity.class);
                startActivity(intent);
            }
        });
        grid_moudlar.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(activity, StoreListActivity.class);
                String tcId = storeType.get(position).getTcId();
                String tcName = storeType.get(position).getLabel();
                //String cityId=SPHelper.getCityId();
                intent.putExtra("tcId", tcId);
                intent.putExtra("tcName", tcName);
                //intent.putExtra("cityId",cityId);
                Log.e(TAG, "---------tcname" + tcName);
                //Log.e(TAG, "---------tcid=" + tcId);
                //Log.e(TAG,"---------cityID="+cityId);
                startActivity(intent);

            }
        });
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Intent intent = new Intent(activity, StoreDetailActivity.class);
                String tsId = storeList.get(i).getTsId();
                intent.putExtra("tsId", tsId);
                startActivity(intent);
            }
        });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        getActivity().unregisterReceiver(mChangeCityReceiver);
    }

    @Override
    public void onResume() {
        super.onResume();
        storeListData(SPHelper.getCityId());
    }

    public void storeTypeData() {
        if (!NetworkUtils.isNetworkAvailable(activity)) {
            activity.showMsg("请检查网络");
        }

        loadingDialog.showDialog();
        loadingDialog.setMsg("正在加载");
        RequestParams params = new RequestParams();
        params.addBodyParameter("", "");

        activity.loadData(HttpRequest.HttpMethod.POST, ApiDefine.STORE_CATRGORY, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> response) {
                //isLoadFinish = true;
                loadingDialog.dismiss();
                Log.e(TAG, "onSuccess response.result" +
                        response.result);
                if (TextUtils.isEmpty(response.result)) {
                    activity.showMsg("本地商城获取失败");
                } else {
                    try {
                        JSONObject jsonObject = new JSONObject(response.result);
                        String code = jsonObject.getString("code");
                        if (code.equalsIgnoreCase("100")) {
                            JSONArray list = jsonObject.getJSONArray("list");
                            for (int i = 0; i < list.length(); i++) {
                                JSONObject temp = list.getJSONObject(i);
                                String tcId = temp.getString("tcId");
                                Log.v(TAG, "-------------------tcid=" + tcId);
                                String tcName = temp.getString("tcName");
                                String tcPic = temp.getString("tcPic");

                                LocalStoreInfo info = new LocalStoreInfo();
                                info.setLabel(tcName);
                                info.setIcon(tcPic);
                                info.setTcId(tcId);
                                storeType.add(info);
                            }
                            mAdapter.setData(storeType);
                            mAdapter.notifyDataSetChanged();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void onFailure(HttpException e, String s) {
                loadingDialog.dismiss();
                activity.showMsg("当前网络不可用，请检查网络设置");
            }
        });

    }

    //获得推荐列表
    private void storeListData(String cityId) {

//        getCityId();
//        String cityId = SPHelper.getCityId();
        RequestParams params = new RequestParams();
        params.addBodyParameter("page", "1");

        //params.addBodyParameter("cityId","87");
        if (!"".equals(cityId)) {
            params.addBodyParameter("cityId", cityId);
            Log.e(TAG, "---------cityid=" + cityId);
        } else {
            params.addBodyParameter("cityId", "1");
        }

        activity.loadData(HttpRequest.HttpMethod.POST, ApiDefine.RECOMMEND_LIST, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> response) {
                loadingDialog.dismiss();
                Log.e(TAG, "onSuccess response.result" +
                        response.result);
                if (TextUtils.isEmpty(response.result)) {
                    activity.showMsg("获取推荐商城失败");
                } else {
                    try {
                        JSONObject jsonObject = new JSONObject(response.result);
                        String code = jsonObject.getString("code");
                        if (code.equalsIgnoreCase("100")) {
                            JSONArray list = jsonObject.getJSONArray("list");
                            storeList.clear();
                            for (int i = 0; i < list.length(); i++) {
                                JSONObject temp = list.getJSONObject(i);
                                String tsName = temp.getString("tsName");
                                String province = temp.getString("province");
                                String city = temp.getString("city");
                                String county = temp.getString("county");
                                String tsLogo = temp.getString("tsLogo");
                                String tsId = temp.getString("tsId");
                                String tsCityId = temp.getString("tsCityId");
                                int tsIntegral = temp.getInt("tsIntegral");

                                LocalStoreInfo info = new LocalStoreInfo();
                                info.setTsId(tsId);
                                info.setStoreName(tsName);
                                info.setProvince(province);
                                info.setCity(city);
                                info.setArea(county);
                                info.setTsLogo(tsLogo);
                                info.setTsIntegral(tsIntegral);

                                storeList.add(info);
                            }
                            mStoreAdapter.setData(storeList);
                            mStoreAdapter.notifyDataSetChanged();

                        }else{
                            storeList.clear();
                            mStoreAdapter.setData(storeList);
                            mStoreAdapter.notifyDataSetChanged();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void onFailure(HttpException e, String s) {
                //loadingDialog.dismiss();
                //activity.showMsg("当前网络不可用，请检查网络");
            }
        });
    }

    public void getCityId() {
        RequestParams params = new RequestParams();
        params.addQueryStringParameter("name",Constant.cName);
        Log.e(TAG, "-----------cName=" + Constant.cName);
        activity.loadData(HttpRequest.HttpMethod.POST, ApiDefine.FIND_LOCATION_BY_NAME, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> response) {
                Log.e(TAG, "cityId  response.result" +
                        response.result);
                try {
                    JSONObject json = new JSONObject(response.result);
                    String code = json.getString("code");
                    if (code.equalsIgnoreCase("100")) {
                        JSONObject result = json.getJSONObject("result");
                        String cityId = result.getString("id");
                        Log.e(TAG, "-----cituid=" + cityId);
                        SPHelper.setCityId(cityId);
                        storeListData(cityId);
                    }else{
                        storeListData("1");
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(HttpException e, String s) {

            }
        });
    }

}
